﻿//泼辣熊 泼辣有图 免费共享图资源获取
var request = require('request'),
    https = require('https'),
    params = require("./initParams.js");
    getAndSaveFileHttp = require("./fileGetAndSaveHttp.js");
    Log = require("./Log.js");

//获取指定资源集合API下的图片资源
function getPic(url) {
    Log.info("资源API：" + url);

    request({
        url: url,
        method: 'GET',
        gzip: true
    }, function (err, res, body) {
        if (err) {
            Log.info("请求失败：" + url);
            Log.error('[ERROR]Collection' + err);
            return;
        }

        var responseObj = JSON.parse(body);

        var datas = responseObj.data;

        if (datas.length === 0) console.log("资源取值超出范围");

        for (var i = 0; i < datas.length; i++) {
            var user_id = datas[i].user_id;
            var id = datas[i].id;
            var full_res = datas[i].full_res;//源文件
            var thumb = datas[i].thumb;//Web展示图
            var user_name = datas[i].user_name;
            var fileName = id + "-" + user_id + ".jpg";

            getAndSaveFileHttp(thumb, params.savePath, fileName);
        }
    });
}

function flowPost() {
    var pageBegin = params.reqParam.pageBegin;
    var pageEnd = params.reqParam.pageEnd;

    if (pageBegin < 0) pageBegin = 1;
    if (pageEnd < pageBegin) pageEnd = pageBegin + 1;

    for (var i = pageBegin; i < pageEnd; i++) {
        var post_url = "http://www.polaxiong.com/collections/get_entries_by_collection_id/" + i + "?{}";

        getPic(post_url);
    }

    process.on("uncaughtException", function (err) {
        //打印出错误
        Log.error("process error: " + err);
        //打印出错误的调用栈方便调试
        Log.error(err.stack);
    });
}

module.exports = flowPost;